package org.darcy.youchat.activity.home;

import android.graphics.Bitmap;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.darcy.youchat.activity.BaseActivity;
import org.darcy.youchat.databinding.ActivityWebviewBinding;
import org.darcy.youchat.utils.StringUtils;


/**
 * 4.内置浏览器界面
 */
public class WebViewActivity extends BaseActivity {

    private ActivityWebviewBinding binding;

    private String mUrl;


    @Override
    public void init() {
        //得到url
        try {
            mUrl = getIntent().getExtras().getString("url");
            if (StringUtils.isEmpty(mUrl)) {
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
            finish();
        }
    }

    @Override
    public void initView() {
        binding = ActivityWebviewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //设置webView
        WebSettings settings = binding.webview.getSettings();
        settings.setSupportMultipleWindows(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setMinimumFontSize(settings.getMinimumLogicalFontSize() + 8);
        settings.setAllowFileAccess(false);
        binding.webview.setVerticalScrollbarOverlay(true);
        binding.webview.setWebViewClient(new MyWebViewClient());
        binding.webview.loadUrl(mUrl);
    }

    @Override
    public void initListener() {
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        //如果当前浏览器可以后退，则后退上一个页面
        if (binding.webview.canGoBack()) {
            binding.webview.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.webview.removeAllViews();
        try {
            binding.webview.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //在自己浏览器中跳转
            binding.webview.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }

}
